package account_manage

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"go_gui/lib"
	"go_gui/logger"
	"go_gui/my_theme"
	"strings"
)

type serverInfo struct {
	Ver      string
	DbHost   string
	Url      string
	DbName   string
	OpenTime string
}

type GameInfo struct {
	Name            string                                     // 游戏名
	GameKey         string                                     // 后台唯一标识
	DefaultServer   string                                     // 默认显示区服
	Server2Info     map[string]*serverInfo                     // 区服
	G123StgMongoUrl string                                     // g123测试服mongo url
	G123ProMongoUrl string                                     // g123正式服mongo url
	DebugSid        int64                                      // 内网sid
	View            func(gameInfo *GameInfo) fyne.CanvasObject // 视图
}

var G123GameKeyList = []string{"jya"}

var G123GameKey2MongoUrl = map[string]map[string]string{
	"jya": {
		"G123StgMongoUrl": "mongodb://jya:密码" +
			"dds-0iw1f61889aa9a641359-pub.mongodb.japan.rds.aliyuncs.com:3717," +
			"dds-0iw1f61889aa9a642239-pub.mongodb.japan.rds.aliyuncs.com:3717" +
			"/?replicaSet=mgset-351473381&authSource=admin",
		"G123ProMongoUrl": "mongodb://jya:密码" +
			"dds-0iw3eed3d3016f041459-pub.mongodb.japan.rds.aliyuncs.com:3717," +
			"dds-0iw3eed3d3016f042796-pub.mongodb.japan.rds.aliyuncs.com:3717" +
			"/?replicaSet=mgset-351764772&authSource=admin",
	},
}

var DefaultMongoUrl = "mongodb://root:iamciniao@10.0.0.9:27017"

var gameName2DefaultServer2Info = map[string]map[string]*serverInfo{}

var gameInfoList = []*GameInfo{
	{
		Name:    "邪神",
		GameKey: "jya",
		Server2Info: map[string]*serverInfo{
			"邪神内网": {
				Ver:    "dev",
				DbHost: "10.0.0.9",
				DbName: "xieshen_s0",
			},
		},
		View: baseView,
	},
	{
		Name: "k",
		Server2Info: map[string]*serverInfo{
			"k内网": {
				Ver:    "dev",
				DbHost: "10.0.0.9",
				DbName: "k_s0",
			},
			"k开发版": {
				Ver:    "dev",
				DbHost: "101.35.121.71",
				Url:    "mongodb://root:iamciniao@101.35.121.71:27017",
				DbName: "k_s10",
			},
		},
		View: baseView,
	},
	//{
	//	Name:    "魔法无敌",
	//	GameKey: "heros",
	//	Server2Info: map[string]*serverInfo{
	//		"魔法无敌内网": {
	//			Ver:    "dev",
	//			DbHost: "10.0.0.9",
	//			//DbHost: "localhost",
	//			DbName: "heros_s0",
	//		},
	//	},
	//	View: baseView,
	//},
	//{
	//	Name:    "像素3",
	//	GameKey: "xiangsu3",
	//	Server2Info: map[string]*serverInfo{
	//		"像素3内网": {
	//			Ver:    "dev",
	//			DbHost: "10.0.0.9",
	//			//DbHost: "localhost",
	//			DbName: "xiangsu3_s0",
	//		},
	//	},
	//	View: baseView,
	//},
	//{
	//	Name:    "童话",
	//	GameKey: "tonghua",
	//	Server2Info: map[string]*serverInfo{
	//		"童话内网": {
	//			Ver:    "dev",
	//			DbHost: "10.0.0.9",
	//			DbName: "tonghua_s0",
	//		},
	//	},
	//	View: baseView,
	//},
	//{
	//	Name:    "诙谐三国",
	//	GameKey: "huixie",
	//	Server2Info: map[string]*serverInfo{
	//		"诙谐内网": {
	//			Ver:    "dev",
	//			DbHost: "10.0.0.9",
	//			DbName: "hxsg_s0",
	//		},
	//	},
	//	View: baseView,
	//},
	//{
	//	Name:        "诙谐三国-繁体",
	//	GameKey:     "huixiefanti",
	//	Server2Info: map[string]*serverInfo{},
	//	View:        baseView,
	//},
}

var (
	allGame   = make([]string, 0)
	treeRoot  = make(map[string][]string)
	game2Info = make(map[string]*GameInfo)
)

func RegisterProject(gameInfo *GameInfo) {
	_g123MongoConfig := G123GameKey2MongoUrl[gameInfo.GameKey]
	if _g123MongoConfig != nil {
		gameInfo.G123StgMongoUrl = _g123MongoConfig["G123StgMongoUrl"]
		gameInfo.G123ProMongoUrl = _g123MongoConfig["G123ProMongoUrl"]
	}

	_name := gameInfo.Name
	game2Info[_name] = gameInfo
	gameName2DefaultServer2Info[_name] = make(map[string]*serverInfo)
	// 存在预定义的区服信息，默认显示
	if len(gameInfo.Server2Info) > 0 {
		for k, info := range gameInfo.Server2Info {
			if info.Url == "" {
				info.Url = DefaultMongoUrl
			}
			if gameInfo.DefaultServer == "" {
				gameInfo.DefaultServer = k
			}
			gameName2DefaultServer2Info[_name][k] = info
		}

	}
	allGame = append(allGame, _name)
	treeRoot[""] = allGame
}

func RemoveProject(gameName string) {
	if !lib.InSlice(gameName, allGame) {
		return
	}

	var idx int
	for chkIdx, chkName := range allGame {
		if gameName == chkName {
			idx = chkIdx
			break
		}
	}
	allGame = append(allGame[:idx], allGame[idx+1:]...)
	treeRoot[""] = allGame
}

func init() {
	for _, gameInfo := range gameInfoList {
		RegisterProject(gameInfo)
	}

}

// NewGameTree 创建一个游戏目录树
func NewGameTree(gameView *fyne.Container) fyne.CanvasObject {
	tree := widget.NewTree(
		// 获取子节点
		func(id widget.TreeNodeID) []widget.TreeNodeID {
			return treeRoot[id]
		},
		// 是否分支
		func(id widget.TreeNodeID) bool {
			_, ok := treeRoot[id]
			return ok
		},
		// 创建节点
		func(b bool) fyne.CanvasObject {
			return container.NewHBox(widget.NewLabel("game name"))
		},
		// 更新节点
		func(id widget.TreeNodeID, b bool, object fyne.CanvasObject) {
			_, ok := game2Info[id]
			if !ok {
				return
			}

			_objects := object.(*fyne.Container).Objects
			// 自定义节点，增加编辑
			if strings.Contains(id, "(add)") {
				object.(*fyne.Container).Objects = []fyne.CanvasObject{
					widget.NewLabel(strings.Split(id, "(add)")[0]),
					&widget.Button{
						Text: "",
						Icon: my_theme.ResourceMythemeEditPng,
						OnTapped: func() {
							EditProjectView(id)
						},
					},
				}
			} else {
				_objects[0].(*widget.Label).SetText(id)
			}

		},
	)

	// 节点选择触发
	tree.OnSelected = func(uid widget.TreeNodeID) {
		_gameInfo, ok := game2Info[uid]
		if !ok {
			logger.FyneLog.Warn(fmt.Sprintf("selectTreeNode node: %s not exists!!", uid))
			return
		}
		CurOwnerList = make([]string, 0)
		_gameInfo.Server2Info = make(map[string]*serverInfo)
		for k, v := range gameName2DefaultServer2Info[_gameInfo.Name] {
			_gameInfo.Server2Info[k] = v
		}
		CurGameInfo = _gameInfo
		gameView.Objects = []fyne.CanvasObject{_gameInfo.View(_gameInfo)}
		gameView.Refresh()
	}

	// 默认选择第一个
	tree.Select(gameInfoList[0].Name)
	AccountComp.GameTree = tree

	return tree
}
